package top.lshaci.learning.springboot.web.fastjson;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.lshaci.learning.springboot.web.fastjson.reader.ObjectReaderMonth;
import top.lshaci.learning.springboot.web.fastjson.reader.ObjectReaderYear;
import top.lshaci.learning.springboot.web.fastjson.reader.ObjectReaderYearMonth;
import top.lshaci.learning.springboot.web.fastjson.writer.*;

import java.time.*;
import java.util.List;

/**
 * FastJson2WebConfig
 *
 * @author liangxu
 */
//@Configuration
public class FastJson2WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = fastJsonHttpMessageConverter.getFastJsonConfig();
        fastJsonConfig.setWriterFeatures(JSONWriter.Feature.WriteEnumsUsingName);
        converters.add(0, fastJsonHttpMessageConverter);

        JSON.register(Year.class, ObjectReaderYear.INSTANCE);
        JSON.register(Month.class, ObjectReaderMonth.INSTANCE);
        JSON.register(YearMonth.class, ObjectReaderYearMonth.INSTANCE);

        JSON.register(Year.class, ObjectWriterYear.INSTANCE);
        // 自定义的枚举Writer不生效
        JSON.register(Month.class, ObjectWriterMonth.INSTANCE);
        JSON.register(YearMonth.class, ObjectWriterYearMonth.INSTANCE);
        JSON.register(LocalDate.class, ObjectWriterLocalDate.INSTANCE);
        JSON.register(LocalTime.class, ObjectWriterLocalTime.INSTANCE);
    }
}
